package com.bootdo.lvyou_specialty.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.utils.*;
import com.bootdo.common.utils.excel.ExportExcel;
import com.bootdo.common.utils.excel.ExportLvyouExcel;
import com.bootdo.common.utils.excel2.DachuExcelUtils;
import com.bootdo.lvyou_specialty.domain.LvyouSpecialtyGzhConfig;
import com.bootdo.lvyou_specialty.service.LvyouSpecialtyGzhConfigService;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;
import com.front.web.lvyou_specialty_front.pagevo.RowSpanVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ModelAttribute;
import com.bootdo.common.controller.BaseController;
import com.bootdo.lvyou_specialty.domain.LvyouSpecialtyOrderContent;
import com.bootdo.lvyou_specialty.service.LvyouSpecialtyOrderContentService;

/**
 * 
 * 
 * @author haojiangbo
 * @email 2100272728@qq.com
 * @date 2019-10-14 09:58:32
 */
 
@Controller
@RequestMapping("/lvyou_specialty/lvyouSpecialtyOrderContent")
public class LvyouSpecialtyOrderContentController extends BaseController{


	@Autowired
	private LvyouSpecialtyOrderContentService lvyouSpecialtyOrderContentService;
	
	@ModelAttribute
	public LvyouSpecialtyOrderContent get(@RequestParam(required=false) Long id) {
		if (id != null){
			return lvyouSpecialtyOrderContentService.get(id);
		}else{
			return new LvyouSpecialtyOrderContent();
		}
	}


	
	//insert into sys_menu(parent_id,name,url,perms,type)  values (149,'测试','/lvyou_specialty/lvyouSpecialtyOrderContent','lvyou_specialty:lvyouSpecialtyOrderContent:lvyouSpecialtyOrderContent',1)
	//insert into sys_menu(parent_id,name,url,perms,type)  values (160,'修改','','lvyou_specialty:lvyouSpecialtyOrderContent:edit',2)
	//type 0是分类菜单 1是小菜但 2是按钮
	@GetMapping()
	@RequiresPermissions("lvyou_specialty:lvyouSpecialtyOrderContent:lvyouSpecialtyOrderContent")	
	String LvyouSpecialtyOrderContent(LvyouSpecialtyOrderContent lvyouSpecialtyOrderContent,HttpServletRequest request,HttpServletResponse response){
	    return "lvyou_specialty/lvyouSpecialtyOrderContent/lvyouSpecialtyOrderContent";
	}
	
	@ResponseBody
	@PostMapping("/list")
	@RequiresPermissions("lvyou_specialty:lvyouSpecialtyOrderContent:lvyouSpecialtyOrderContent")
	public PageUtils list(@RequestParam Map<String, Object> params,
						  @RequestParam(value = "selectedMerchantIds", defaultValue = "")String selectedMerchantIds){
		//查询列表数据

		String selectedMerchantIds1 = (String) params.get("selectedMerchantIds");

		if (StringUtils.isNotEmpty(selectedMerchantIds)) {
			try {
				Long[] longs = JSON.parseObject(selectedMerchantIds, Long[].class);
				params.put("selectedMerchantIds", longs);
			}catch (Exception e) {
				params.remove("selectedMerchantIds");
			}
		} else {
			params.remove("selectedMerchantIds");
		}


		Query query = new Query(params);
		List<LvyouSpecialtyOrderContent> lvyouSpecialtyOrderContentList = lvyouSpecialtyOrderContentService.list(query);

		Map<String, Integer> rowSpanMap = new HashMap<>();
		if (params.get("merchantFlag") != null) {
			for (LvyouSpecialtyOrderContent one: lvyouSpecialtyOrderContentList) {
				if (rowSpanMap.containsKey(one.getGoodsOrderNo())) {
					rowSpanMap.put(one.getGoodsOrderNo(), rowSpanMap.get(one.getGoodsOrderNo()) + 1);
				} else {
					rowSpanMap.put(one.getGoodsOrderNo(), 0);
				}
			}
		}

		int total = lvyouSpecialtyOrderContentService.count(query);
		PageUtils pageUtils = new PageUtils(lvyouSpecialtyOrderContentList, total);
		return pageUtils;
	}

	@ResponseBody
	@PostMapping("/listGongying")
	@RequiresPermissions("lvyou_specialty:lvyouSpecialtyOrderContent:lvyouSpecialtyOrderContent")
	public R listGongying(@RequestParam Map<String, Object> params,
						  @RequestParam(value = "selectedMerchantIds", defaultValue = "")String selectedMerchantIds){
		//查询列表数据

		String selectedMerchantIds1 = (String) params.get("selectedMerchantIds");

		if (StringUtils.isNotEmpty(selectedMerchantIds)) {
			try {
				Long[] longs = JSON.parseObject(selectedMerchantIds, Long[].class);
				params.put("selectedMerchantIds", longs);
			}catch (Exception e) {
				params.remove("selectedMerchantIds");
			}
		} else {
			params.remove("selectedMerchantIds");
		}


		Query query = new Query(params);
		List<LvyouSpecialtyOrderContent> lvyouSpecialtyOrderContentList = lvyouSpecialtyOrderContentService.list(query);

		Map<String, RowSpanVo> rowSpanMap = null;
		if (params.get("merchantFlag") != null) {
			rowSpanMap = new HashMap<>();
			for (LvyouSpecialtyOrderContent one: lvyouSpecialtyOrderContentList) {
				if (rowSpanMap.containsKey(one.getGoodsOrderNo())) {
					RowSpanVo rowSpanVo = rowSpanMap.get(one.getGoodsOrderNo());
					rowSpanVo.setNumber(rowSpanVo.getNumber() + 1);
				} else {
					RowSpanVo rowSpanVo = new RowSpanVo();
					rowSpanVo.setContentId(one.getId());
					rowSpanVo.setNumber(0);
					rowSpanMap.put(one.getGoodsOrderNo(), rowSpanVo);
				}
			}
			query.remove("merchantFlag");
		}

		int total = lvyouSpecialtyOrderContentService.count(query);

		return R.ok().put("rows", lvyouSpecialtyOrderContentList).put("total", total).put("rowSpanMap", rowSpanMap);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("lvyou_specialty:lvyouSpecialtyOrderContent:edit")
	String add(LvyouSpecialtyOrderContent lvyouSpecialtyOrderContent,HttpServletRequest request,HttpServletResponse response){
	    return "lvyou_specialty/lvyouSpecialtyOrderContent/lvyouSpecialtyOrderContentedit";
	}

	@PostMapping("/getById")
	@ResponseBody
	R getById(LvyouSpecialtyOrderContent lvyouSpecialtyOrderContent) {
		return R.ok().put("i",lvyouSpecialtyOrderContent);
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("lvyou_specialty:lvyouSpecialtyOrderContent:edit")
	public R save( LvyouSpecialtyOrderContent lvyouSpecialtyOrderContent){
	
		if(lvyouSpecialtyOrderContentService.save(lvyouSpecialtyOrderContent)>0){
			return R.ok();
		}
		return R.error();
	}
	
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("lvyou_specialty:lvyouSpecialtyOrderContent:edit")
	public R remove( Long id){
		if(lvyouSpecialtyOrderContentService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("lvyou_specialty:lvyouSpecialtyOrderContent:edit")
	public R remove(@RequestParam("ids[]") Long[] ids){
		lvyouSpecialtyOrderContentService.batchRemove(ids);
		return R.ok();
	}

	/**
	 * 编辑物流信息
	 * @param ids
	 * @return
	 */
	@PostMapping( "/editDelivery")
	@ResponseBody
	@RequiresPermissions("lvyou_specialty:lvyouSpecialtyOrderContent:edit")
	public R editDelivery(@RequestParam(value = "orderNo", defaultValue = "")String orderNo,
						  @RequestParam(value = "logisticsType", defaultValue = "")String logisticsType,
						  @RequestParam(value = "logisticsNumber", defaultValue = "")String logisticsNumber){
		if (StringUtils.isEmpty(logisticsNumber) || StringUtils.isEmpty(logisticsType) ||  StringUtils.isEmpty(orderNo) ) {
			return R.error("参数错误");
		}

		if (lvyouSpecialtyOrderContentService.editDelivery(orderNo, logisticsType, logisticsNumber) == 0) {
			return R.error("发货失败，请检查订单状态");
		}

		return R.ok().put("i", orderNo);
	}

//	@RequestMapping("/exportExcel/content")
//	public void exportExcelContent(@RequestParam Map<String, Object> params,
//								   HttpServletRequest request,
//								   HttpServletResponse response){
//		System.out.println(params);
//		if (StringUtils.isNotEmpty((String)params.get("limit"))) {
//			params.put("limit", Integer.parseInt((String) params.get("limit")));
//		}
//		if (StringUtils.isNotEmpty((String)params.get("offset"))) {
//			params.put("offset", Integer.parseInt((String) params.get("offset")));
//		}
//
//		List<LvyouSpecialtyOrderContent> list = lvyouSpecialtyOrderContentService.list(params);
//		if (params.get("limit") != null) {
//			params.remove("limit");
//		}
//		if (params.get("offset") != null) {
//			params.remove("offset");
//		}
//		ExportExcel exportExcel = new ExportExcel("订单汇总表", LvyouSpecialtyOrderContent.class);
//		exportExcel.setDataList(list);
//		try {
//			exportExcel.write(response, "汇总表.xls");
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}

	@RequestMapping("/exportExcel/content")
	public void exportExcelContent(@RequestParam("query") String query,
								   HttpServletRequest request,
								   HttpServletResponse response){
		JSONObject param = null;
		try {
			param = JSON.parseObject(query);
		} catch (Exception e) {
			String result = JSON.toJSONString(R.error("参数有误"));
			response.setStatus(200);
			response.setContentType("application/json");
			response.setCharacterEncoding("utf-8");
			try {
				response.getWriter().write(result);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}

		if (param.get("limit") != null) {
			param.remove("limit");
		}

		if (param.get("offset") != null) {
			param.remove("offset");
		}

		List<LvyouSpecialtyOrderContent> list = lvyouSpecialtyOrderContentService.list(param);

		Map<String, List<LvyouSpecialtyOrderContent>> dealMap = new HashMap<>();

		for (LvyouSpecialtyOrderContent one: list) {
			String key = one.getMerchantId() + one.getMerchantName();
			if (dealMap.containsKey(key)) {
				List<LvyouSpecialtyOrderContent> contentList = dealMap.get(key);
				contentList.add(one);
			} else {
				List<LvyouSpecialtyOrderContent> listOne = new ArrayList<>();
				listOne.add(one);
				dealMap.put(key, listOne);
			}
		}

		try {
			new DachuExcelUtils<LvyouSpecialtyOrderContent>().exportExcle("订单统计-" + DateUtils.format(new Date()), LvyouSpecialtyOrderContent.class, list, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
//		ExportLvyouExcel exportExcel = new ExportLvyouExcel("订单汇总表", LvyouSpecialtyOrderContent.class, dealMap);
//		exportExcel.setDataList();
//		try {
//			exportExcel.write(response, "汇总表.xls");
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
	}

}